import yaml
def read_yaml(file:str):
    with open(file, 'r', encoding='utf-8') as file:
        data = yaml.safe_load(file)
    return data
def write_yaml(file:str,data:dict):
    # with open(file, 'a', encoding='utf-8') as file:
    #     yaml.dump(data, file, default_flow_style=False, allow_unicode=True)
    def merge_dicts(d1, d2):
        for k in d2:
            if k in d1 and isinstance(d1[k], dict) and isinstance(d2[k], dict):
                merge_dicts(d1[k], d2[k])
            else:
                d1[k] = d2[k]
    with open(file, 'r', encoding='utf-8') as f:
        existing_data = yaml.safe_load(f)
    if bool(existing_data):
        #合并字典
        merge_dicts(existing_data, data)
    else:
        existing_data = data
    # 将合并后的数据写回 YAML 文件
    with open(file, 'w', encoding='utf-8') as f:
        yaml.safe_dump(existing_data, f, default_flow_style=False, allow_unicode=True)
    print(f"{file} 文件已成功更新")
